import React, { useCallback, Suspense, useMemo } from 'react';
import { Switch, Route, useSearchParams } from "react-router-dom";
import { rootRouter, otherRouter } from './routerData'
import ErrorBoundary from 'src/components/ErrorBoundary'
import NotFound from 'src/components/NotFound'

const getRouter = ({ routerData, open_tab, root = "/" }) => {
    return routerData.map(({ path, exact, Component }) => {
        return <Route
            path={`${root === '/' ? '' : root}${path}`}
            key={path}
            exact={exact || false}
            component={() => {
                return (
                    <ErrorBoundary>
                        <Suspense>
                            <Component open_new_tab={open_tab} />
                        </Suspense>
                    </ErrorBoundary>
                )
            }}
        />
    }
    );
};

const open_new_window_tab = (link, title, src) => {
    let url = `${window.location.origin}/#/${link}`
    if (src) {
        //如果是iframe直接打开iframe
        url = src.startsWith('/') ? `${window.location.origin}${src}` : src
    }
    try {
        window.open('javascript:window.name;', `<script>location.replace("${url}")</script>`);
    } catch (e) {
        //window.open(url);
        //window.open(link, '', 'height=500,width=611,scrollbars=yes,status =yes')
    }
}

const Router = (props) => {
    const { path: root } = useSearchParams();
    const { open_new_tab } = props;
    const open_tab = useCallback((link, title, src) => {
        if (open_new_tab) {
            open_new_tab(link, title, src)
        } else {
            open_new_window_tab(link, title, src)
        }
    }, [open_new_tab])

    const otherRouterElement = useMemo(() => {
        return getRouter({ routerData: otherRouter, open_tab, root })
    }, [otherRouter, open_tab, root])

    const rootRouterElement = useMemo(() => {
        return root === '/' && getRouter({ routerData: rootRouter, open_tab, root })
    }, [rootRouter, open_tab, root])

    return <Switch>
        {
            rootRouterElement
        }
        {otherRouterElement}
        <Route>
            <NotFound />
        </Route>
    </Switch>
}

export default Router;

//tips:这里如果不定义变量Router，写成 export default ()=>{} 则页面不会自动热更新，why???
//原因：箭头函数需要先声明给一个变量，再export default